import { NextRequest, NextResponse } from 'next/server'

export async function POST(request: NextRequest) {
  try {
    const { keyword } = await request.json()

    if (!keyword) {
      return NextResponse.json(
        { error: '请提供搜索关键词' },
        { status: 400 }
      )
    }

    // 调用TikHub API搜索TikTok视频
    const searchResults = await searchTikTokVideos(keyword, 5)
    
    return NextResponse.json({
      success: true,
      keyword,
      count: searchResults.length,
      videos: searchResults.map(video => ({
        id: video.aweme_id,
        title: video.desc?.substring(0, 100) || '无标题',
        author: video.author?.nickname || video.author?.unique_id || 'Unknown',
        likes: video.statistics?.digg_count || 0,
        views: video.statistics?.play_count || 0,
        duration: video.video?.duration ? Math.floor(video.video.duration / 1000) : 0,
        publishTime: video.create_time ? new Date(video.create_time * 1000).toISOString() : null
      }))
    })

  } catch (error) {
    console.error('Test TikHub API error:', error)
    return NextResponse.json(
      { 
        error: '测试失败', 
        details: error instanceof Error ? error.message : '未知错误' 
      },
      { status: 500 }
    )
  }
}

// 调用TikHub API搜索TikTok视频
async function searchTikTokVideos(keyword: string, count: number = 10) {
  const API_KEY = process.env.TIKHUB_API_KEY || '9r8Ie1BX3l8NgQlSwFe1m3A/8gA7zaXbi5R232rau1Ny1VMqUeZN1x65Ng=='

  // 构建查询参数
  const params = new URLSearchParams({
    keyword: keyword,
    offset: '0',
    count: count.toString(),
    sort_type: '0', // 0-相关度，1-最多点赞
    publish_time: '0' // 0-不限制，1-最近一天，7-最近一周，30-最近一个月，90-最近三个月，180-最近半年
  })

  const TIKHUB_API_URL = `https://api.tikhub.io/api/v1/tiktok/app/v3/fetch_general_search_result?${params}`

  console.log('调用TikHub API:', { keyword, count, apiKey: API_KEY.substring(0, 10) + '...' })

  try {
    const response = await fetch(TIKHUB_API_URL, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${API_KEY}`,
        'Accept': 'application/json'
      }
    })

    console.log('TikHub API响应状态:', response.status)

    if (!response.ok) {
      const errorText = await response.text()
      console.error('TikHub API错误响应:', errorText)
      throw new Error(`TikHub API error: ${response.status} ${response.statusText} - ${errorText}`)
    }

    const result = await response.json()
    console.log('TikHub API响应:', {
      code: result.code,
      dataLength: result.data?.data?.length || 0
    })

    if (result.code === 200 && result.data && result.data.data) {
      return result.data.data.map((item: any) => item.aweme_info).filter(Boolean)
    } else {
      throw new Error(`TikHub API returned error: ${result.message || 'Unknown error'}`)
    }
  } catch (error) {
    console.error('TikHub API call failed:', error)
    throw error
  }
}
